from flask import Blueprint, request, render_template, flash, abort
from app.models import Article, Tag
from app import db

home_article = Blueprint("home_article", __name__)

@home_article.route("/detail")
def index():
    aid = request.args.get('aid')
    try:
        article = Article.query.filter_by(id=aid).first()
    except Exception as e:
        flash(str(e))
        abort(500)

    # 获取相关
    tag_id = []
    for t in article.tags:
        tag_id.append(t.id)
    
    try:
        relation = Article.query.filter(Tag.id.in_(tag_id)).order_by(Article.click.desc()).limit(8).all()
        # 获取同一分类
        channel = Article.query.filter_by(category_id=article.category_id, is_state=1).order_by(Article.click.desc()).limit(8).all()
        # 设置阅读次数
        article.click += 1
        db.session.add(article)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        flash(str(e))
        abort(500)

    return render_template("home/article.html", article=article, channel=channel, relation=relation)